package com.cong.project.utils;

import com.cong.project.common.ErrorCode;
import com.cong.project.exception.BusinessException;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * minio工具类
 *
 * @author 86188
 * @date 2023/01/30
 */
@Service
public class MinioUtils {
    @Autowired
    private MinioClient minioClient;
    @Value("${minio.bucketName}")
    private String bucketName;

    @Value("${minio.endpoint}")
    private String endpoint;


    public List<String> upload(@RequestParam(name= "file",required =false) MultipartFile[] file){
        if (file ==null|| file.length ==0){
            return null;
        }
        List<String> originalFilenameList = new ArrayList<>(file.length);
        for (MultipartFile multipartFile : file) {
            String originalFilename = multipartFile.getOriginalFilename();
            originalFilenameList.add(endpoint+"/"+bucketName+"/"+originalFilename);
            try {
                InputStream inputStream = multipartFile.getInputStream();
                minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(originalFilename).stream(
                        inputStream, multipartFile.getSize(), -1
                ).contentType(multipartFile.getContentType()).build());
                inputStream.close();
            } catch (Exception e) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }

        }
        return originalFilenameList;
    }
}
